<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChSmartPushScheme;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Config\Annotation\Value;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;

class ChSmartPushSchemeMapper extends AbstractMapper
{
    #[Value('cache.default.prefix')]
    protected string $prefix;

    public function assignModel()
    {
        $this->model = ChSmartPushScheme::class;
    }

    /**
     * 根据主键获取数据
     * @param mixed $id
     * @return ChSmartPushScheme|Model|string|Builder|null
     */
    #[Cacheable(prefix: 'smart_push_scheme',value: 'id_#{id}',ttl: 15 * 60)]
    public function findById(mixed $id): ChSmartPushScheme|Model|string|Builder|null
    {
        return $this->model::query()
            ->where('id',$id)
            ->first();
    }

    /**
     * 删除缓存
     * @param mixed $id
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \RedisException
     */
    public function delCache(mixed $id): void
    {
        $redis = redis();
        $keyOne = $this->prefix . 'smart_push_scheme:id_'.$id;
        $redis->del([$keyOne]);
    }

    /**
     * 获取方案列表
     * @param array $params
     * @return array
     */
    public function getSchemeList(array $params): array
    {
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;
        $query = ChSmartPushScheme::query()
            ->select(['id','title','push_type','status','contact_count','reach_count','completed_count','created_at']);
        $paginate =  $this->handleSearch($query,$params)->orderByDesc('id')->paginate((int)$pageSize);
        return  $this->setPaginate($paginate);
    }


    public function handleSearch(Builder $query, array $params): Builder
    {
        if(!empty($params['id'])){
            $query->where('id',$params['id']);
        }

        $query->where('uid',$params['uid']);

        if(!empty($params['keyword'])){
            $query->where('title','like','%'.$params['keyword'].'%');
        }

        if(isset($params['status']) && filled($params['status'])){
            $query->where('status',$params['status']);
        }

        if(isset($params['type']) && filled($params['type'])){
            $query->where('push_type',$params['type']);
        }

        if(!empty($params['start_time']) && !empty($params['end_time'])){
            $query->whereBetween('created_at',[$params['start_time'],$params['end_time']]);
        }

        return $query;
    }
}